<template>
  <Dialog :title="dialogTitle" v-model="dialogVisible" modal-append-to-body="true" append-to-body="true">
    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      label-width="150px"
      v-loading="formLoading"
    >
      
      <el-form-item label="道路名称" prop="dlmc">
        <el-select v-model="formData.dlmc" filterable placeholder="请选择道路名称">
          <el-option
            v-for="dict in intersection"
            :key="dict.bh"
            :label="dict.dlmc"
            :value="dict.bh"
             @click="onClickintersection(dict)"
          />
        </el-select>
      </el-form-item>

      <el-form-item label="杆件路口方向" prop="fx">
        <el-select v-model="formData.fx" placeholder="请选择杆件路口方向"  ref="fx">
          <el-option
            v-for="dict in getStrDictOptions(DICT_TYPE.ROAD_DIRECTION)"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
            @click="onClickfx(dict)"
          />
        </el-select>
      </el-form-item>

      <el-form-item label="杆件编号(自动生成)" prop="gjbh">
        <el-input v-model="formData.gjbh" placeholder="杆件编号默认自动生成" readonly />
      </el-form-item>
      <el-form-item label="杆件名称(自动生成)" prop="gjmc">
        <el-input v-model="formData.gjmc" placeholder="杆件名称默认自动生成" readonly />
      </el-form-item>

      <el-form-item label="所属部门" prop="ssbm">
        <el-select v-model="formData.ssbm" placeholder="请选择杆件所属部门">
          <el-option
            v-for="dict in bmlist"
            :key="dict.id"
            :label="dict.name"
            :value="dict.name" 
          />
        </el-select>
      </el-form-item>

    </el-form>
    <template #footer>
      <el-button @click="submitForm" type="primary" :disabled="formLoading">确 定</el-button>
      <el-button @click="dialogVisible = false">取 消</el-button>
    </template>
  </Dialog>
</template>
<script setup lang="ts">
import { getStrDictOptions, DICT_TYPE,DEVICE_DIRECTION } from '@/utils/dict'
import { barinfoApi, barinfoVO } from '@/api/barinfo/barinfo'
import { intersectionApi,   } from '@/api/intersection/intersection'

/** 杆件 表单 */
defineOptions({ name: 'BarinfoForm' })
const props = defineProps<{
  dlbh?: String // 道路编号（主表的关联字段）
}>()

const bhognval = ref()

const { t } = useI18n() // 国际化
const message = useMessage() // 消息弹窗

const dialogVisible = ref(false) // 弹窗的是否展示
const dialogTitle = ref('') // 弹窗的标题
const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const formType = ref('') // 表单的类型：create - 新增；update - 修改
const formData = ref({
  id: undefined,
  fx: undefined,
  dlmc: undefined,
  dlbh:undefined,
  ssbm:undefined,
  gjbh: undefined,
  gjmc:undefined,
  fxmc:undefined,
})
 
const formRef = ref() // 表单 Ref
const fx =ref()

/** 查询列表 */
const intersection = ref<Record<string, any>[]>([]);
const getintersectionList = async () => { 
  try {
    if(props.dlbh){
      const data = await intersectionApi.getintersectionPage({pageNo:1, pageSize:1000,bh: props.dlbh})
      intersection.value =  data.list;

      
    }else{
      const data = await intersectionApi.getintersectionPage({pageNo:1, pageSize:1000})
      intersection.value =  data.list;
    }
    
  } finally {
     
  }
}
getintersectionList()

const bmlist = ref<Record<string, any>[]>([]);
const getbmlist = async () => { 
  try {
    const data = await intersectionApi.deptsimple({})
      bmlist.value =  data;
    
  } finally {
     
  }
}
getbmlist()

const validatorfx = async(_rule, value, callback)=> {   
  console.log("formType.value ",formType.value )
  if(formType.value =='create'){
    const data = await intersectionApi.getGJList({fx: formData.value.fx, dlmc: formData.value.dlmc})
    if(data.total!=0){
    callback(new Error('该方向的道路杆件已经录入'));
    } else {
      callback( );
    }
  }else{ 
    const data = await intersectionApi.getGJList({fx: formData.value.fx, dlmc: formData.value.dlmc})
    if(data.total!=0 && data.list[0].id != bhognval.value){
    callback(new Error('该方向的道路已经录入'));
    } else {
      callback( );
    }
  }
  
}
const formRules = reactive({
  ////调用接口判断是否已经有对应方向，对应道路的杆件，有的话直接报错提示
  
  fx:[{required:true, message:"请选择杆件所在路口方向"},
  { validator:validatorfx}
  ],
  dlmc:[{required:true, message:"请选择道路、交叉路口"} ],
  //gjbh:[{required:true, message:"请输入杆件编号"} ],
  //gjmc:[{required:true, message:"请输入杆件名称"} ]
})

const  onClickintersection = (dict) =>{ 
  formData.value.gjbh = dict.bh + ((typeof formData.value.fx =="undefined") ?'':formData.value.fx)

  formData.value.gjmc = dict.dlmc + ((typeof formData.value.fxmc =="undefined") ?'':formData.value.fxmc)+'立杆' 
  formData.value.dlbh = dict.bh
  formData.value.dlmc = dict.dlmc
}
const onClickfx = (dict) =>{
  formData.value.gjbh =  ((typeof formData.value.dlbh =="undefined") ?'':formData.value.dlbh) + dict.value
  formData.value.fxmc=dict.label
  formData.value.gjmc =  ((typeof formData.value.dlbh =="undefined") ?'':formData.value.dlmc) + dict.label+'立杆' 

  
}


/** 打开弹窗 */
const open = async (type: string, id?: number) => {
  dialogVisible.value = true
  dialogTitle.value = t('action.' + type)
  formType.value = type
  resetForm()
  // 修改时，设置数据
  if (id) {
    formLoading.value = true
    try {
      formData.value = await barinfoApi.getbarinfo(id)
      bhognval.value = formData.value.id
      
    } finally {
      formLoading.value = false
    }
  }else{
    //formData.value.dlmc = props.dlbh
    formData.value.gjbh = dict.bh + ((typeof formData.value.fx =="undefined") ?'':formData.value.fx)
  }
}
defineExpose({ open }) // 提供 open 方法，用于打开弹窗

/** 提交表单 */
const emit = defineEmits(['success']) // 定义 success 事件，用于操作成功后的回调
const submitForm = async () => {
  // 校验表单
  await formRef.value.validate()
  // 提交请求
  formLoading.value = true
  try {
    const data = formData.value as unknown as barinfoVO
    if (formType.value === 'create') {
      await barinfoApi.createbarinfo(data)
      message.success(t('common.createSuccess'))
    } else {
      await barinfoApi.updatebarinfo(data)
      message.success(t('common.updateSuccess'))
    }
    dialogVisible.value = false
    // 发送操作成功的事件
    emit('success')
  } finally {
    formLoading.value = false
  }
}

/** 重置表单 */
const resetForm = () => {
  formData.value = {
    id: undefined,
    fx: undefined,
    dlmc: undefined,
    gjbh: undefined,
    gjmc:undefined,
  }
  formRef.value?.resetFields()
}
</script>